package com.ia.aistream.manager.framework.redis.impl;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.ia.aistream.manager.framework.redis.RedisStringManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author chenjunsheng
 */
@Service
public class RedisStringManagerImpl implements RedisStringManager {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void set(String key, Object value) {
        redisTemplate.opsForValue().set(key, JSON.toJSONString(value));
    }

    @Override
    public void set(String key, Object value, long time, TimeUnit unit) {
        redisTemplate.opsForValue().set(key, JSON.toJSONString(value), time, unit);
    }

    @Override
    public Boolean setnx(String key, Object value) {
        return redisTemplate.opsForValue().setIfAbsent(key, JSON.toJSONString(value));
    }

    @Override
    public void setex(String key, int seconds, Object value) {
        redisTemplate.opsForValue().set(key, JSON.toJSONString(value), seconds, TimeUnit.SECONDS);
    }

    @Override
    public void psetex(String key, long milliseconds, Object value) {
        redisTemplate.opsForValue().setIfPresent(key, JSON.toJSONString(value), milliseconds, TimeUnit.MILLISECONDS);
    }

    @Override
    public <T> T get(String key, Class<T> clazz) {
        String value = redisTemplate.opsForValue().get(key);
        return JSON.parseObject(value, clazz);
    }

    @Override
    public <T> T getSet(String key, T value) {
        String old = redisTemplate.opsForValue().getAndSet(key, JSON.toJSONString(value));
        return JSON.parseObject(old, value.getClass().asSubclass(value.getClass()));
    }

    @Override
    public Long strLen(String key) {
        return redisTemplate.opsForValue().size(key);
    }

    @Override
    public Long incr(String key) {
        return redisTemplate.opsForValue().increment(key, 1);
    }

    @Override
    public void incrby(String key, long increment) {
        redisTemplate.opsForValue().increment(key, increment);
    }

    @Override
    public void incrbyfloat(String key, double increment) {
        redisTemplate.opsForValue().increment(key, increment);
    }

    @Override
    public <T> List<T> mget(Collection<String> keys, Class<T> clazz) {
        List<String> list = redisTemplate.opsForValue().multiGet(keys);
        if (CollectionUtils.isEmpty(list)) {
            return Lists.newArrayList();
        }
        List<T> result = Lists.newArrayList();
        for (String value : list) {
            result.add(JSON.parseObject(value, clazz));
        }
        return result;
    }
}
